<template>

  <div :style="{height:height+30+'px',width:width}">
    <el-button v-if="!loading" type="success" icon="el-icon-download" size="mini" @click="getChartImage">导出报告</el-button>
    <div class="chart" ref="linechart" :style="{height:height+'px',width:width}"></div>
  </div>
</template>

<script>
 import * as echarts from 'echarts';
 require('echarts/theme/macarons'); // echarts theme
 import resize from './mixins/resize';

 export default {
   mixins: [resize],
   props: {
     className: {
       type: String,
       default: 'chart'
     },
     width: {
       type: String,
       default: '100%'
     },
     height: {
       type: Number,
       default: window.innerHeight - 100,
     },
     text: {
       type: String,
       default: ''
     },
     unit:{
       type:Number,
       default:1024,
     },
     subtext: {
       type: String,
       default: ''
     },
     chartData: {
       type: Object,
       required: true
     }
   },
   watch: {
     chartData: {
       deep: true,
       handler(val, oldValue) {
         // 使用节流技术来控制更新频率
         this.throttleSetOptions(val);
       }
     },
     subtext: {
       deep: true,
       handler(val) {
         this.subtext = val;
       }
     },
     unit:{
       deep: true,
       handler(val) {
         this.unitShow=val
       }
     },
     text: {
       deep: true,
       handler(val) {
         this.text = val;
       }
     }
   },
   data() {
     return {
       loading: false,
       chart: null,
       dataURL: '',
       unitShow:this.unit,
       mapping: {
         'ONE_DAY': '1天',
         'ONE_DAY_TO_ONE_WEEK': '1天-1星期',
         'ONE_WEEK_TO_ONE_MONTH': '1星期-1月',
         'ONE_MONTH_TO_SIX_MONTHS': '1月-6月',
         'SIX_MONTHS_TO_ONE_YEAR': '6月-1年',
         'ONE_YEAR_TO_TWO_YEARS': '1年-2年',
         'GREATER_THAN_TWO_YEARS': '>2年',
       },
       _xDataCache: null,
     }
   },
   mounted() {
     this.$nextTick(() => {
       this.initChart();
     })
   },
   beforeDestroy() {
     if (!this.chart) {
       return;
     }
     this.chart.dispose();
     this.chart = null;
   },
   methods: {
     getChartImage() {
       this.loading = true;
       this.dataURL = this.chart.getDataURL({
         type: 'png',
         pixelRatio: 2,
       });
       this.$emit('handleSetSetChartImage', this.dataURL);
       this.loading = false;
     },
     replaceValues(array, map) {
       if (!this._xDataCache) {
         this._xDataCache = array.map(item => map[item] || item);
       }
       return this._xDataCache;
     },
     initChart() {
       this.chart = echarts.init(this.$refs.linechart, 'macarons');
       this.setOptions(this.chartData);
     },
     throttleSetOptions: _.throttle(function(summaryData) {
       this.setOptions(summaryData);
     }, 300), // 控制更新频率，单位毫秒

     setOptions(summaryData) {
       if (!this.chart) {
         console.error('Chart instance is not initialized.');
         return;
       }

       let xData = this.replaceValues(Object.keys(summaryData), this.mapping);

       // 使用 requestAnimationFrame 来异步更新图表
       requestAnimationFrame(() => {
         this.chart.setOption({
           title: {
             text: this.text,
             subtext: this.subtext,
             left: 'center'
           },
           tooltip: {
             trigger: 'axis',
             axisPointer: {
               type: 'cross',
             }
           },
           toolbox: {
             feature: {
               // dataView: {
               //   show: true,
               //   readOnly: false
               // },
               // magicType: {
               //   show: true,
               //   type: ['line', 'bar']
               // },
             }
           },
           xAxis: [{
             type: 'category',
             data: xData,
             axisPointer: {
               type: 'shadow'
             }
           }],
           yAxis: [{
               type: 'value',
               name: '容量',
               axisLabel: {
                 formatter: '{value}'
               }
             },
             {
               type: 'value',
               name: '容量',
               axisLabel: {
                 formatter: '{value}'
               }
             }
           ],
           series: [{
               name: '容量',
               type: 'bar',
               label: {
                 show: true,
                 position: 'outside',
                 formatter: '{b}: {c}'+(this.unitShow==1?'B':this.unitShow==1024?'KB':this.unitShow==1024*1024?'MB':this.unitShow==1024*1024*1024?'GB':'个') // 显示数值
               },
               tooltip: {
                 valueFormatter: function(value) {
                   return value;
                 }
               },
               data: Object.values(summaryData),
               // itemStyle: {
               //   color: function(params) {
               //     const colors = ['#5793f3', '#d14a61', '#675bba', '#ffa022', '#2f4554', '#91c7ae', '#00aaff'];
               //     return colors[params.dataIndex];
               //   }
               // }
             },
             {
               name: '容量',
               type: 'line',
               yAxisIndex: 1,
               tooltip: {
                 valueFormatter: function(value) {
                   return value;
                 }
               },
               data: Object.values(summaryData),
               itemStyle: {
                 color: '#ffa022'
               }
             }
           ]
         });
       });
     }
   }
 };
</script>
